package io.coding.controller;

import io.coding.model.Bl_message_board;
import io.coding.service.MessageBoardService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * Created by Administrator on 2014/9/9.
 */
@Controller
public class MessageBoardController {

    @Autowired
    MessageBoardService messageBoardService;

    @RequestMapping(value = "/messageBoard")
    public String findAll(Model model) {
        List<Bl_message_board> ref = messageBoardService.findAll();
        model.addAttribute("list", ref);
        return "message/messageboard";
    }

    @RequestMapping(value = "/AddMessageBoard")
    public String AddMessageBoard(String content, String source_ip) {
        messageBoardService.AddMessageBoard(content, source_ip);
        return "redirect:/messageBoard";
    }

    /**
     * 获取访问者IP
     * <p/>
     * 在一般情况下使用Request.getRemoteAddr()即可，但是经过nginx等反向代理软件后，这个方法会失效。
     * <p/>
     * 本方法先从Header中获取X-Real-IP，如果不存在再从X-Forwarded-For获得第一个IP(用,分割)，
     * 如果还不存在则调用Request .getRemoteAddr()。
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!StringUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!StringUtil.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }


}
